// Learn cc.Class:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

const GameDataManger = require("../GameDataManger");
const UIPanelManager = require("../UIPanelManager");

cc.Class({
    extends: cc.Component,

    properties: {
        layoutNode:{    
            default:null,
            type:cc.Node
        },

        gradeLab:{     
            default:null,
            type:cc.Label
        },

        gradeNumLab:{     
            default:null,
            type:cc.Label
        },

        gradeIcon:{     
            default:null,
            type:cc.Sprite
        },
    },

    onEnable(){
        this.refresh();
    },

    refresh(){
        this.isCur = false;
        for (let index = 0; index < GameDataManger.gradConfig.length; index++) {
            const element = this.layoutNode.children[index];
            if (!element){
                element = cc.instantiate(this.layoutNode.children[0]);
                element.parent = this.layoutNode;
            }
            this.refreshItem(element, GameDataManger.gradConfig[index]);
        }
    },

    loadIamge(image, iconName){
        let url = 'imags/grades/' + iconName
        cc.resources.load(url, cc.SpriteFrame, (err, asset) => {
            if (err){
                console.log("资源加载失败")
                return;
            }
            image.getComponent(cc.Sprite).spriteFrame = asset;
        });
    },

    refreshItem(itemNode, data){
        itemNode.getChildByName("gradeLab").getComponent(cc.Label).string = data.name;

        itemNode.getChildByName("gradeNumLab").getComponent(cc.Label).string = data.score;

        this.loadIamge(itemNode.getChildByName("gradeIcon"), data.icon)

        if (GameDataManger.selfScore >= data.score && !this.isCur){
            this.isCur = true;
            itemNode.getChildByName("isCur").active = true;

            this.gradeLab.string = data.name;
            this.gradeNumLab.string = GameDataManger.selfScore;
            this.loadIamge(this.gradeIcon, data.icon)

            GameDataManger.selfGrade = data.id;
        }else{
            itemNode.getChildByName("isCur").active = false;
        }

    },

    btnClick(event,str){
        if (str == "matchBtn"){
            UIPanelManager.open(UIPanelManager.matchNode);
        }
    },

    onDisable(){
    },

    // update (dt) {},
});
